const express = require("express");
const router = express.Router();
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");

dayjs.extend(utc);
dayjs.extend(timezone);

let connectDAO = require("./connect.js");

// 用户注册
router.post("/register", function (req, res) {
  const { UserName, PassWord, PhoneNumber, Role } = req.body;

  const sql = `INSERT INTO User 
    (UserName, PassWord, PhoneNumber, Role) 
    VALUES 
    ('${UserName}', '${PassWord}', '${PhoneNumber}',  '${Role || "Student"}')`;

  connectDAO.queryDataBySQL(sql, (result) => {
    res.send({
      code: 200,
      msg: "注册成功",
      data: { UserID: result.insertId }
    });
  }, (err) => {
    if (err.code === 'ER_DUP_ENTRY') {
      const msg = err.sqlMessage.includes('UserName') ? '用户名已存在' :
        err.sqlMessage.includes('PhoneNumber') ? '手机号已注册' :
          '邮箱已被使用';
      res.send({ code: 409, msg });
    } else {
      res.send({ code: 500, msg: "服务器错误" });
    }
  });
});

// 登陆
router.get("/login", function (req, res) {
  const { UserName, PassWord } = req.query;
  const sql = `SELECT * FROM User 
                WHERE UserName = '${UserName}' AND PassWord = '${PassWord}'`;

  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.length > 0) {
      res.send({
        code: 200,
        msg: "登录成功",
        data: records[0]
      });
    } else {
      res.send({
        code: 401,
        msg: "用户名或密码错误"
      });
    }
  });
});

// 获取用户列表（带分页）
router.get("/users", function (req, res) {
  const { page = 1, pageSize = 10, Role } = req.query;
  const offset = (page - 1) * pageSize;

  let whereClause = "";
  if (Role) {
    whereClause = `WHERE Role = '${Role}'`;
  }

  const countSQL = `SELECT COUNT(*) AS total FROM User ${whereClause}`;
  const dataSQL = `
     SELECT *
     FROM User 
     ${whereClause}
     ORDER BY CreateTime DESC
     LIMIT ${pageSize} OFFSET ${offset}
   `;

  connectDAO.queryDataBySQL(countSQL, (countResult) => {
    const total = countResult[0].total;
    connectDAO.queryDataBySQL(dataSQL, (records) => {
      res.send({
        code: 200,
        msg: "Success",
        data: {
          records,
          total,
          current: parseInt(page),
          size: parseInt(pageSize)
        }
      });
    });
  });
});

// 更新用户信息
router.put("/users", function (req, res) {
  const { Class, UserID, FaceUrl } = req.body;
  let sql = `UPDATE User SET `;//Class = '${Class}',FaceUrl='${FaceUrl}' WHERE UserID = ${UserID}
  if (Class) {
    sql += ` Class = '${Class}'`
    if (FaceUrl) {
      sql += `, FaceUrl = '${FaceUrl}'`
    }
  }
  if (FaceUrl && !Class) {
    sql += ` FaceUrl='${FaceUrl}'`
  }
  sql += ` WHERE UserID = ${UserID}`
  connectDAO.queryDataBySQL(sql, () => {
    res.send({ code: 200, msg: "success" });
  });
});


module.exports = router;